<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>let关键字</title>
</head>

<body>

    <button>1</button>
    <button>2</button>
    <button>3</button>
    <button>4</button>
    <button>5</button>

</body>

<script>
    var button = document.getElementsByTagName('button');
    //let的作用域比较小
    //以下代码第一种触发的i都是4、因为var作用域广泛所以都是使用最后一个索引
    for (var i = 0; i < button.length; i++) {
        button[i].onclick = function() {
            alert(i);
        }

    }

    //其二解决方案
    for (var i = 0; i < button.length; i++) {
        button[i].onclick = function() {
            for (var i = 0; i < button.length; i++) {
                if (this == button[i]) {
                    alert(i);
                }
            }
        }
    }

    //使用let关键字来解决
    for (let i = 0; i < button.length; i++) {
        button[i].onclick = function() {
            alert(i);
        }
    }
</script>


</html>